using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Concurrent;

namespace Taxhui.Utils.Network.UtilityHelper
{
    public class LogHelper : IDisposable
    {
        private readonly ConcurrentQueue<string> _que; //日志队列
        private bool _isruning = true; //运行标志
        private static Task _writeThread; //写文件线程

        #region 写日志进入队列
        public void WriteLog(string log)
        {
            if (!this._isruning) return;
            _que.Enqueue(log);
        }
        #endregion
        #region 构造函数
        public LogHelper()
        {
            _que = new ConcurrentQueue<string>();
            //线程对象为NULL的时候启动写入线程
            if(null == _writeThread)
            {
                _writeThread = new Task(WriteFile);
                _writeThread.Start();
            }
            
        }
        #endregion
        #region 写文件
        private void WriteFile()
        {
            while (_isruning)
            {
                try
                {
                    //只有在队列不为空的时候才写
                    if (!_que.IsEmpty)
                    {
                        var sw = new System.IO.StreamWriter("Network.log", true);
                        string tmp = "";
                        while (!_que.IsEmpty)
                        {
                            if (_que.TryDequeue(out tmp))
                                sw.WriteLine("time：{0} -- {1}", DateTime.Now, tmp);
                        }
                        sw.Close();
                    }
                }
                catch
                {
                }
                Thread.Sleep(100);
            }
        }
        #endregion
        #region 析构函数
        public void Dispose()
        {
            _isruning = false;
            _writeThread = null;
        }
        #endregion
    }
}
